import os
import sys
import galscript
from pydub import AudioSegment
from pydub.utils import mediainfo

class WolfSound(galscript.ScriptLine):
    def __init__(self, index, text, processor):
        super().__init__(index, text, processor)

    def process(self):
        # 去除末尾可能存在的逗号
        cleaned_str = self.text.rstrip(',')

        # 分割字符串
        parts = [part.strip() for part in cleaned_str.split(',')]

        # 提取各个参数
        file = parts[0].strip('"')  # 去除两边的引号
        # 空文件名不处理
        if len(file) == 0:
            return self.discard()

        volume = int(parts[1]) if len(parts) > 1 else 0
        frequency = int(parts[2]) if len(parts) > 2 else 0
        offset = int(parts[3]) if len(parts) > 3 else 0

        full_path = os.path.join(self.processor.assets_dir, file)
        time = self.get_audio_duration(full_path)

        print(f"[{self.index}/{self.processor.size()}]{file} {time}s")

        self.add_attr_test("Volume", volume, 0)
        self.add_attr_test("Frequency", frequency, 0)
        self.add_attr_test("Offset", offset, 0)
        self.xml = f'    <Item Index="{self.index}" Time="{time}" {self.attr}>{file}</Item>'
        pass

    def get_audio_duration(self, file_path):
        """获取音频时长（秒）"""
        try:
            audio = AudioSegment.from_file(file_path)
            return len(audio) / 1000.0  # 毫秒转秒
        except Exception as e:
            print(f"无法读取音频文件 {file_path}: {str(e)}", file=sys.stderr)
            return 0

def process_file(input_file, assets_dir):
    processor = galscript.ScriptProcessor(input_file, lambda idx,name,processor: WolfSound(idx,name,processor))
    processor.assets_dir = assets_dir
    processor.process()
    processor.save()

    print(f"处理完成！结果已保存到: {processor.output_file}")

if __name__ == "__main__":
    args = galscript.FileManager()  # 使用imodule中的Args类
    input_file = args.get_str("file")
    assets_dir = args.get_str("assets", "")
    process_file(input_file, assets_dir)